package com.mzba.place.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.MediaStore;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.Toast;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.mzba.place.BasicActivity;
import com.mzba.place.R;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.RegisterEntity;
import com.mzba.place.ui.widget.ArrayAdapter;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
import com.mzba.place.utils.Utils;
/**
 * 
 * @author 06peng
 *
 */
public class UpdateUserInfoActivity extends BasicActivity implements Callback {
	
	private ImageView ivAvatar;
	private EditText tvNickname;
	private EditText tvEmail;
	private EditText tvPassword;
	private EditText tvMobile;
	
	private Handler handler;
	private WeakReference<Bitmap> avatarBitmap = null;
	
	private final int menu_confirm = 0x10010;
	private final int activity_result_camara_with_data = 1006;
    private final int activity_result_cropimage_with_data = 5;
    private final int load_avatar = 0x10011;
    private final int update_exist = 0x10012;
    private final int update_error = 0x10013;
	
	private File picFile;
    private Uri photoUri;
    private String avatar;
    private RegisterEntity entity;

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle("完善资料");
		setSupportProgressBarIndeterminateVisibility(false);
		setContentView(R.layout.update_userinfo);
		tvNickname = (EditText) findViewById(R.id.nickname_et);
		ivAvatar = (ImageView) findViewById(R.id.avatar_iv);
		tvEmail = (EditText) findViewById(R.id.email_et);
		tvPassword = (EditText) findViewById(R.id.password_et);
		tvMobile = (EditText) findViewById(R.id.mobile_et);
		ivAvatar.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				doPickPhotoAction();
			}
		});
		UserTable ut = new UserTable(this);
		entity = ut.get();
		init();
	}
	
	private void init() {
		if (entity == null) {
			return;
		}
		if (StringUtil.isNotBlank(entity.getUsername())) {
			tvNickname.setText(entity.getUsername());
		}
		if (StringUtil.isNotBlank(entity.getEmail())) {
			tvEmail.setText(entity.getEmail());
		}
		if (StringUtil.isNotBlank(entity.getTelphone())) {
			tvMobile.setText(entity.getTelphone());
		}
		if (StringUtil.isNotBlank(entity.getAvatar_url())) {
			avatar = entity.getAvatar_url();
			UICore.eventTask(this, this, load_avatar, null, false);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, menu_confirm, 0, "设置").setIcon(R.drawable.abs__ic_cab_done_holo_dark)
				.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		case menu_confirm:
			if (StringUtil.isBlank(tvNickname.getText().toString().trim())) {
				Toast.makeText(this, "昵称不能为空！", Toast.LENGTH_SHORT).show();
				return false;
			} else if (!StringUtil.checkLoginAccount(tvNickname.getText().toString().trim())) {
				Toast.makeText(this, "用户名必须包含英文,数字,或者下划线！", Toast.LENGTH_SHORT).show();
				return false;
			}
			if (StringUtil.isBlank(tvEmail.getText().toString().trim())) {
				Toast.makeText(this, "邮箱不能为空！", Toast.LENGTH_SHORT).show();
				return false;
			} else if (!StringUtil.isValidEmail(tvEmail.getText().toString().trim())) {
				Toast.makeText(this, "邮箱格式错误！", Toast.LENGTH_SHORT).show();
				return false;
			}
			if (StringUtil.isNotBlank(tvMobile.getText().toString().trim()) &&
					!StringUtil.isMobile(tvMobile.getText().toString().trim())) {
				Toast.makeText(this, "手机格式错误！", Toast.LENGTH_SHORT).show();
				return false;
			}
			if (StringUtil.isNotBlank(tvPassword.getText().toString().trim())
					&& tvPassword.getText().toString().trim().length() < 8) {
				Toast.makeText(this, "密码不能小于8位数！", Toast.LENGTH_SHORT).show();
				return false;
			}
			UICore.eventTask(this, this, menu_confirm, null, true);
			break;
		}
		return false;
	}
	
	private void update() {
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
		paramsMap.put("user[email]", tvEmail.getText().toString().trim());
		paramsMap.put("user[telphone]", tvMobile.getText().toString().trim());
		paramsMap.put("user[username]", tvNickname.getText().toString().trim());
		if (StringUtil.isNotBlank(tvPassword.getText().toString().trim())) {
			paramsMap.put("user[password]", tvPassword.getText().toString().trim());
		}
		try {
			String  result = null;
			if (picFile != null) {
				result = HttpUtils.put(UrlConfig.update, paramsMap, picFile);
			} else {
				result = HttpUtils.put(this, UrlConfig.update, paramsMap);
			}
			if (StringUtil.isNotBlank(result)) {
				JSONObject obj = new JSONObject(result);
				if (obj.optString("error").equals("EMAIL EXIST")) {
					handler.sendEmptyMessage(update_exist);
				} else {
					if (StringUtil.isNotBlank(obj.optString("username"))) {
						entity.setUsername(obj.optString("username"));
					}
					if (StringUtil.isNotBlank(obj.optString("email"))) {
						entity.setEmail(obj.optString("email"));
					}
					if (StringUtil.isNotBlank(obj.optString("telphone"))) {
						entity.setTelphone(obj.optString("telphone"));
					}
					if (StringUtil.isNotBlank(obj.optString("avatar"))) {
						entity.setAvatar_url(obj.optString("avatar"));
					}
					UserTable ut = new UserTable(UpdateUserInfoActivity.this);
					ut.save(entity);
					handler.sendEmptyMessage(menu_confirm);
				}
			} else {
				handler.sendEmptyMessage(update_error);
			}
		} catch (Exception e) {
			handler.sendEmptyMessage(update_error);
			e.printStackTrace();
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case menu_confirm:
			update();
			break;
		case load_avatar:
			avatarBitmap = new WeakReference<Bitmap>(Utils.getBitmap(this, avatar));
            if (avatarBitmap.get() != null) {
            	handler.sendEmptyMessage(load_avatar);
            }
			break;
		}
	}
	
	private void doPickPhotoAction() {
        final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
        String cancel = getString(R.string.confirm_back);
        String[] choices;
        choices = new String[2];
        choices[0] = getString(R.string.expand_edit_take_photo); // 拍照
        choices[1] = getString(R.string.expand_edit_choose_photo); // 从相册中选择
        final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
                        android.R.layout.simple_list_item_1, choices);

        final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
        builder.setTitle(R.string.system_info);
        builder.setSingleChoiceItems(adapter, -1,
                        new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        switch (which) {
                                        case 0:
                                                String status = Environment.getExternalStorageState();
                                                if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
                                                	doTakePhoto();// 用户点击了从照相机获取
                                                }
                                                break;
                                        case 1:
                                                doCropPhoto();// 从相册中去获取
                                                break;
                                        }
                                }
                        });
        builder.setNegativeButton(cancel,
                        new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                }

                        });
        builder.create().show();
	}
	
	protected void doTakePhoto() {
		try {
			File uploadFileDir = new File(AppContext.getSDPath(), "upload");
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			if (!uploadFileDir.exists()) {
				uploadFileDir.mkdirs();
			}
			picFile = new File(uploadFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
			startActivityForResult(cameraIntent,
					activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void doCropPhoto() {
		try {
			File pictureFileDir = new File(AppContext.getSDPath(), "upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			final Intent intent = getCropImageIntent();
			startActivityForResult(intent, activity_result_cropimage_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Constructs an intent for image cropping. µ˜”√Õº∆¨ºÙº≠≥Ã–Ú
	 */
	public Intent getCropImageIntent() {
	        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
	        intent.setType("image/*");
	        intent.putExtra("crop", "true");
	        intent.putExtra("aspectX", 1);
	        intent.putExtra("aspectY", 1);
	        intent.putExtra("outputX", 600);
	        intent.putExtra("outputY", 600);
	        intent.putExtra("noFaceDetection", true);
	        intent.putExtra("scale", true);
	        intent.putExtra("return-data", false);
	        intent.putExtra("scaleUpIfNeeded", true);
	        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
	        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	        return intent;
	}
	
	private void cropImageUriByTakePhoto() {
	         Intent intent = new Intent("com.android.camera.action.CROP");
	         intent.setDataAndType(photoUri, "image/*");
	         intent.putExtra("crop", "true");
	         intent.putExtra("aspectX", 1);
	         intent.putExtra("aspectY", 1);
	         intent.putExtra("outputX", 600);
	         intent.putExtra("outputY", 600);
	         intent.putExtra("scale", true);
	         intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
	         intent.putExtra("return-data", false);
	         intent.putExtra("scaleUpIfNeeded", true);
	         intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
	         intent.putExtra("noFaceDetection", true); // no face detection
	         startActivityForResult(intent, activity_result_cropimage_with_data);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case activity_result_camara_with_data:
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case activity_result_cropimage_with_data:
			try {
				if (photoUri != null) {
					Bitmap bitmap = decodeUriAsBitmap(photoUri);
					ivAvatar.setImageBitmap(bitmap);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}
	

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case load_avatar:
				ivAvatar.setImageBitmap(avatarBitmap.get());
				break;
			case menu_confirm:
				Intent intent = new Intent();
                intent.setAction("update_avatar");
                sendBroadcast(intent);
				Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT).show();
				break;
			case update_error:
				Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT).show();
				break;
			case update_exist:
				Toast.makeText(this, "该email已经绑定了用户，去登录！", Toast.LENGTH_SHORT).show();
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	protected void onDestroy() {
		super.onDestroy();
		try {
			 File uploadFileDir = new File(AppContext.getSDPath(), "upload");
             File file = new File(uploadFileDir, "upload.jpeg");
             if (file.exists()) {
                     file.delete();
             }
			if (avatarBitmap != null && avatarBitmap.get() != null && !avatarBitmap.get().isRecycled()) {
				avatarBitmap.get().recycle();
				avatarBitmap = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
